package com.zhuojy.equity.mall.admin.core;

import cn.hutool.core.util.ObjUtil;
import com.zhuojy.equity.mall.admin.common.enums.ErrCdEnum;
import com.zhuojy.equity.mall.admin.common.exception.Asserts;
import com.zhuojy.equity.mall.admin.common.exception.BizException;
import com.zhuojy.equity.mall.admin.dal.dataobject.TUserDO;
import com.zhuojy.equity.mall.admin.manager.UserManager;
import com.zhuojy.equity.mall.admin.manager.bo.RegisterBO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * 用户注册核心事务
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RegisterCore {

	private final PasswordEncoder passwordEncoder;

	private final UserManager userManager;

	/**
	 * 检查用户是否存在
	 */
	public void checkUserExisted(RegisterBO registerBO) throws BizException {
		TUserDO tUserDO = userManager.queryUserByUsername(registerBO.getUsername());
		if (ObjUtil.isNotNull(tUserDO)) {
			// 用户已存在
			Asserts.fail(ErrCdEnum.B004);
		}
	}

	/**
	 * 用户注册
	 */
	public void registerUser(RegisterBO registerBO) throws BizException {
		// 将密码进行加密操作
		String encodePassword = passwordEncoder.encode(registerBO.getPassword());
		registerBO.setPassword(encodePassword);
		boolean registerUserOk = userManager.registerUser(registerBO);
		if (!registerUserOk) {
			// 添加用户失败
			Asserts.fail(ErrCdEnum.B005);
		} else {
			registerBO.setRegisterResult(true);
		}
	}
}
